<template>
  <div class="row">
    <div class="col-sm-12 col-md-12 col-lg-12">
      <div class="panel panel-default">
        <div class="panel-heading">
          <div class="row header">
            <div class="col-sm-4 col-md-4 col-lg-4">
              <strong>发布管理系统</strong>
            </div>
          </div>
        </div>
        <div class="panel-body">
          <DeployLogDialog ref="deploy"></DeployLogDialog>
          <div class="spinner" v-if="loading">
            <div class="rect1"></div>
            <div class="rect2"></div>
            <div class="rect3"></div>
            <div class="rect4"></div>
            <div class="rect5"></div>
          </div>
          <ul class="list-group" v-if="items.length > 0">
            <li class="list-group-item" :key=index v-for="(item, index) in items">
              <div class="row">
                <div class="col-sm-6 col-md-6 col-lg-6"><strong>{{item.name}}</strong> - {{item.intro?item.intro:'无'}}</div>
                <div class="col-sm-6 col-md-6 col-lg-6 text_align_right">
                  <button type="button" class="btn b btn-primary btn-sm" v-bind:class="{ disabled: item.isRunning }" v-bind:disabled="item.isRunning" @click="execute(index)">{{item.deployBtn}}</button>
                  <button type="button" class="btn b btn-default btn-sm" @click="showlog(index)">查看日志</button>
                </div>
              </div>
            </li>
          </ul>
          <p class="text-center" v-if="items.length == 0 && loading==false">没有符合条件的数据</p>
        </div>
      </div>
    </div>
  </div>
</template>

<style src="@/assets/loading.css" scoped></style>

<style scoped>
a,a:hover {text-decoration:none;}
.btn.b {
  margin-left:3px;
  margin-right:3px;
}
strong {font-size:16px;}
.label {
  margin-right:3px;
}
/*
.list-group-item {
  display:flex;
  flex-direction:row;
  justify-content:space-between;
}
*/
/* 小屏幕（平板，大于等于 768px） */
@media (min-width: 768px) {
  .text_align_right {text-align:right;}
}
@media (max-width: 768px) {
  .header > div {
    margin:6px 0;
  }
}
</style>
<script>

import DeployLogDialog from '@/components/DeployLogDialog.vue'

export default {
  name: 'index',
  components: {
    DeployLogDialog
  },
  data: function () {
    return {
      items: [],
      loading: true
    }
  },
  created: function () {
    this.axios
      .post('/cmdlist')
      .then((res) => {
        this.loading = false
        this.items = res.data
        this.items.forEach(function (n, i) {
          n['isRunning'] = false
          n['deployBtn'] = '开始部署'
        })
      })
      .catch((err) => {
        this.errorResponse(err)
      })
  },
  mounted () {
    window.addEventListener('beforeunload', e => this.beforeunloadFn(e))
  },
  destroyed () {
    window.removeEventListener('beforeunload', e => this.beforeunloadFn(e))
  },
  methods: {
    ws () {
      let url = 'ws://' + location.host + '/deploy'
      // 创建websocket连接
      this.websock = new WebSocket(url)
      // 监听打开
      this.websock.onopen = this.websockOpen
      // 监听关闭
      this.websock.onclose = this.websockClose
      // 监听异常
      this.websock.onerror = this.websockError
      // 监听服务器发送的消息
      this.websock.onmessage = this.websockMessage
    },
    websockOpen () {
    },
    websockClose () {
    },
    websockError () {
    },
    websockMessage (e) {
      let index = e.data.indexOf(':')
      let id = e.data.substring(0, index)
      let msg = e.data.substring(index + 1)
      if (/end部署/.test(msg)) {
        this.btnRun(id, false)
        msg = msg.replace('end', '')
      }
      this.$refs.deploy.push(id, msg)
    },
    errorResponse (err) {
      if (err.response && err.response.data && err.response.status === 200) {
        var data = err.response.data
        alert(data.ErrorMessage + '#' + data.ErrorCode)
        var errorList = []
        data.ErrorList.forEach(item => {
          for (var key in item) {
            errorList.push(item[key] + '#' + key)
          }
        })
        alert(errorList.join('\n'))
      } else {
        alert('服务器异常，请稍后再试')
      }
    },
    btnRun (index, isRun) {
      var n = {}
      if (isRun) {
        n = {
          isRunning: true,
          deployBtn: '正在部署中...'
        }
      } else {
        n = {
          isRunning: false,
          deployBtn: '开始部署'
        }
      }
      n = $.extend(this.items[index], n)
      this.$set(this.items, index, n)
    },
    execute (index) {
      this.btnRun(index, true)
      this.ws()
      this.showlog(index)
      setTimeout(() => {
        this.websock.send(index)
      }, 500)
    },
    showlog (index) {
      this.$refs.deploy.show(index)
    },
    beforeunloadFn (e) {
      let isRunning = false
      this.items.forEach(function (n, i) {
        if (n['isRunning'] === true) {
          isRunning = true
        }
      })
      // 兼容IE8和Firefox 4之前的版本
      if (isRunning === true) {
        e = e || window.event
        if (e) {
          e.returnValue = '关闭提示'
        }
        // Chrome, Safari, Firefox 4+, Opera 12+ , IE 9+
        return '关闭提示'
      }
    }
  }
}
</script>
